package com.hindua.utils;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;

import com.hindua.ailaaicuaai.NoNetworkActivity;

public class NetworkState {
	private Context context;
	
	public NetworkState(Context context) {
		this.context = context;
	}
	
	public boolean hasConnection() {
		/*
		ConnectivityManager conmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = conmgr.getActiveNetworkInfo();
		if (activeInfo != null) {
			if (activeInfo.getState() == State.CONNECTED) {
				try {
					URL uri = new URL("http://www.google.com.vn");
					HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
					int response = conn.getResponseCode();
					if (response == HttpURLConnection.HTTP_OK) {
						return true;
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
		*/
		return checkNetWork();
	}
	
	public boolean checkNetWork() {
		final ConnectivityManager connManager = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifi.isAvailable() && wifi.isConnectedOrConnecting()) {
			//Toast.makeText(this, "Wifi", Toast.LENGTH_SHORT).show();
			return true;
		}
		final NetworkInfo mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (mobile.isAvailable() && mobile.isConnectedOrConnecting()) {
			//Toast.makeText(this, "3G", Toast.LENGTH_SHORT).show();
			return true;
		}
		//Toast.makeText(this, "No Network !", Toast.LENGTH_SHORT).show();
		return false;
	}
	
	public void check() {
		/*
		ConnectivityManager conmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = conmgr.getActiveNetworkInfo();
		if (activeInfo != null) {
			if (activeInfo.getState() == State.CONNECTED) {
				try {
					URL uri = new URL("http://www.google.com.vn");
					HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
					int response = conn.getResponseCode();
					if (response == HttpURLConnection.HTTP_OK) {
						return;
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}*/
		boolean check_network = checkNetWork();
		if (!check_network) {
			((FragmentActivity) context).finish();
			Intent intent = new Intent(context, NoNetworkActivity.class);
			intent.putExtra("INTENT", ((FragmentActivity) context).getIntent());
			context.startActivity(intent);
		}
	}
}
